﻿CREATE PROCEDURE dbo.PurgeTakeoutUsers
(
	@PurgeMinutesThreshold int
)

AS

UPDATE dbo.TakeoutProvider SET MaximumOrders = MaximumOrders + 1 WHERE ID IN (
	SELECT     dbo.TakeoutProvider.Id
	FROM         dbo.TakeoutUser INNER JOIN
	                      dbo.TakeoutProvider ON dbo.TakeoutUser.TakeoutProviderID = dbo.TakeoutProvider.Id
	WHERE     (dbo.TakeoutProvider.AllowPayMeLater = 0) AND (dbo.TakeoutUser.IsPaid = 0) AND (DATEDIFF(minute, dbo.TakeoutUser.OrderTime, GETDATE()) > @PurgeMinutesThreshold)
)

DELETE FROM dbo.TakeoutUser WHERE Id IN (
	SELECT     dbo.TakeoutUser.Id
	FROM         dbo.TakeoutUser INNER JOIN
	                      dbo.TakeoutProvider ON dbo.TakeoutUser.TakeoutProviderID = dbo.TakeoutProvider.Id
	WHERE     (dbo.TakeoutProvider.AllowPayMeLater = 0) AND (dbo.TakeoutUser.IsPaid = 0) AND (DATEDIFF(minute, dbo.TakeoutUser.OrderTime, GETDATE()) > @PurgeMinutesThreshold)
)
	
	/* SET NOCOUNT ON */
	RETURN


